// 设置 STOMP 客户端
window.stompClient = null

// 设置 WebSocket 进入端点
var SOCKET_ENDPOINT = "/web-socket-communication"
// 设置订阅消息的请求地址前缀
var SUBSCRIBE_PREFIX  = "/notify"
// 设置订阅地址
var SUBSCRIBE = ""
// 设置服务器端点，访问服务器中哪个接口
var SEND_ENDPOINT = "/web-socket/to-user"      // 一对一发送给用户
var SEND_ENDPOINT_CHAT = "/web-socket/chatroom"      // 聊天室

var subscribes = {}


/* 进行连接 */
function connect(callback) {
    if (stompClient != null && stompClient.connected){
        return
    }
    layui.use(['hash'], function() {
        // 设置 SOCKET
        var socket = new SockJS(SOCKET_ENDPOINT)

        // 配置 STOMP 客户端
        stompClient = Stomp.over(socket)
        // STOMP 客户端连接
        stompClient.connect({}, function () {
            callback("ok")
        }, function (err) {
            callback("no")
        })
    })
}

/* 订阅信息 */
function subscribeSocket(value, flag, callback){
    // 清除订阅缓存，防止重复订阅
    if (subscribes[value]){
        subscribes[value].unsubscribe()
        delete subscribes[value]
    }
    // 执行订阅消息
    subscribes[value] = stompClient.subscribe(value, function (responseBody) {
        let receiveMessage = JSON.parse(responseBody.body)
        layui.use(['notice'], function () {
            let notice = layui.notice

            notice.options = {
                closeButton: true,//显示关闭按钮
                positionClass: "toast-bottom-right",//弹出的位置,
                showDuration: "300",//显示的时间
                hideDuration: "500",//消失的时间
                timeOut: "5000",//停留的时间(5s)
                extendedTimeOut: "3000", //控制时间(3s)
            }

            if (callback)
                callback(receiveMessage)

            if (receiveMessage.destination === SUBSCRIBE_PREFIX + "/system/chatroom") return

            if (receiveMessage.content !== "user-out")
                notice.info(receiveMessage.from + "：" + receiveMessage.content)

        })
    })
}

/* 断开连接 */
function disconnect() {
    stompClient.disconnect(function() {

    })
}

/* 发送消息并指定目标地址 */
function sendMessageNoParameter(user, content) {
    // 设置待发送的消息内容
    let message = '{"targetUser":"' + user + '", "destination": "' + SUBSCRIBE_PREFIX + "/" + user + '", "content": "' + content + '"}'
    // 发送消息
    stompClient.send(SEND_ENDPOINT, {}, message)
}

function sendChatRoomNews(fromName, content) {
    let message = {
        targetUser: "all",
        destination: SUBSCRIBE_PREFIX + "/system/chatroom",
        content: content,
        fromName: fromName
    }
    stompClient.send(SEND_ENDPOINT_CHAT, {}, JSON.stringify(message))
}